package com.qunar.dyds.controller;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import jxl.Workbook;
import jxl.write.Label;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.WriteException;
import jxl.write.biff.RowsExceededException;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.qunar.base.meerkat.util.DateUtil;
import com.qunar.base.meerkat.util.StringUtil;
import com.qunar.base.meerkat.web.codelist.MappedCodeListLoader;
import com.qunar.common.admin.constant.WebConstants;
import com.qunar.dyds.dto.ListObject;
import com.qunar.dyds.entity.Competitor;
import com.qunar.dyds.entity.CompetitorStatus;

@Controller("competitor")
public class CompetitorController extends AbstractController {

    @RequestMapping(value = "list")
    public ModelAndView list(@RequestParam(value = "inviteCode", required = false) String code,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "school", required = false) String school,
            @RequestParam(value = "major", required = false) String major,
            @RequestParam(value = "startIndex", required = false, defaultValue = "0") int startIndex,
            @RequestParam(value = "row", required = false, defaultValue = WebConstants.DEFAULT_PAGE_SIZE_STR) int row) {

        Map<String, Object> cond = new HashMap<String, Object>();
        cond.put("inviteCode", code);
        cond.put("name", name);
        cond.put("status", status);
        cond.put("school", school);
        cond.put("major", major);

        // 查询总记录数
        int totalCount = competitorService.getCount(cond);

        // 查询记录列表
        List<Competitor> beans = competitorService.search(cond, startIndex, row);

        // 绑定结果列表
        ListObject lstObj = new ListObject(startIndex, row, totalCount, beans);
        ModelAndView view = new ModelAndView("competitor/list");
        view.addObject("lstObj", lstObj);
        view.addObject("inviteCode", code);
        view.addObject("cond", cond);

        return view;
    }

    @RequestMapping(value = "detail", method = RequestMethod.GET)
    public ModelAndView detail(@RequestParam("id") Integer id) {

        Competitor competitor = competitorService.get(id);
        return new ModelAndView("competitor/detail", "item", competitor);
    }

    @RequestMapping(value = "active", method = RequestMethod.GET)
    public String active(@RequestParam("id") Integer id,
            @RequestParam(value = "forward", required = false) String forward) {
        return updateStatus(id, CompetitorStatus.ACTIVED, forward);
    }

    @RequestMapping(value = "lock", method = RequestMethod.GET)
    public String lock(@RequestParam("id") Integer id, @RequestParam(value = "forward", required = false) String forward) {
        return updateStatus(id, CompetitorStatus.LOCKED, forward);
    }

    @RequestMapping(value = "delete", method = RequestMethod.GET)
    public String delete(@RequestParam("id") Integer id,
            @RequestParam(value = "forward", required = false) String forward) {

        return updateStatus(id, CompetitorStatus.DELETED, forward);
    }

    protected String updateStatus(int id, int status, String forward) {
        Competitor competitor = new Competitor();
        competitor.setId(id);
        competitor.setStatus(status);
        competitor.setUpdated(new Date());

        try {
            competitorService.update(competitor);
        } catch (Exception e) {
            logger.error("update status failed, e={}, id={}", e, id);
        }

        if (!StringUtil.isEmpty(forward)) {
            return "redirect:" + forward;
        }

        return "redirect:/competitor/list.htm";
    }

    @RequestMapping(value = "export")
    public void export(@RequestParam(value = "inviteCode", required = false) String code,
            @RequestParam(value = "name", required = false) String name,
            @RequestParam(value = "status", required = false) Integer status,
            @RequestParam(value = "school", required = false) String school,
            @RequestParam(value = "major", required = false) String major, HttpServletResponse response) {

        Map<String, Object> cond = new HashMap<String, Object>();
        cond.put("inviteCode", code);
        cond.put("name", name);
        cond.put("status", status);
        cond.put("school", school);
        cond.put("major", major);

        // 查询记录列表
        List<Competitor> beans = competitorService.search(cond);

        // 下载文件
        String filename = getDownloadFileName(cond);
        response.setContentType("application/vnd.ms-excel");
        response.addHeader("Content-Disposition", "attachment;   filename=\"" + filename + "\"");

        OutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
            export(outputStream, beans);
            response.flushBuffer();
        } catch (Exception e) {
            logger.error("export excel failed, e={}, cond={}", e, cond);
        } finally {
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                }
            }
        }
    }

    @Resource(name = "competitorStatusLoader")
    protected MappedCodeListLoader competitorStatusLoader;

    /**
     * 下载文件名
     * 
     * @param cond 查询条件
     * @return
     */
    protected String getDownloadFileName(Map<String, Object> cond) {
        Iterator<String> iter = cond.keySet().iterator();
        StringBuilder sb = new StringBuilder("导游信息_");
        while (iter.hasNext()) {
            String key = iter.next();
            Object value = cond.get(key);
            if (value == null || "".equals(value)) {
                continue;
            }
            if ("status".equals(key)) {
                sb.append(competitorStatusLoader.getCodeListMap().get(value.toString()));
            } else {
                sb.append(value);
            }
            sb.append("_");
        }
        String timestamp = DateUtil.format(new Date(), DateUtil.PATTERN_YYYY_MM_DD_HH_MM_SS);

        return StringUtil.encodeURL(sb.toString()) + timestamp + ".xls";
    }


    protected void export(OutputStream outputStream, List<Competitor> beans) throws IOException, RowsExceededException,
            WriteException {

        // 工作表
        WritableWorkbook workbook = Workbook.createWorkbook(outputStream);

        // 工作表单
        WritableSheet sheet = workbook.createSheet("导游信息", 0);
        sheet.addCell(new Label(0, 0, "ID"));
        sheet.addCell(new Label(1, 0, "报名序号"));
        sheet.addCell(new Label(2, 0, "姓名"));
        sheet.addCell(new Label(3, 0, "年龄"));
        sheet.addCell(new Label(4, 0, "学校"));
        sheet.addCell(new Label(5, 0, "专业"));
        sheet.addCell(new Label(6, 0, "年级"));
        sheet.addCell(new Label(7, 0, "手机号码"));
        sheet.addCell(new Label(8, 0, "电子邮件"));
        sheet.addCell(new Label(9, 0, "用户名"));
        sheet.addCell(new Label(10, 0, "票数"));
        sheet.addCell(new Label(11, 0, "创建时间"));
        sheet.addCell(new Label(12, 0, "更新时间"));
        sheet.addCell(new Label(13, 0, "状态"));
        sheet.addCell(new Label(14, 0, "个人简介"));
        // sheet.addCell(new Label(10, 0, "密码"));

        int row = 0;
        for (int i = 0; i < beans.size(); i++) {
            Competitor item = beans.get(i);
            row = i + 1;

            sheet.addCell(new Label(0, row, String.valueOf(item.getId())));
            sheet.addCell(new Label(1, row, item.getInviteCode()));
            sheet.addCell(new Label(2, row, item.getName()));
            sheet.addCell(new Label(3, row, String.valueOf(item.getAge())));
            sheet.addCell(new Label(4, row, item.getSchool()));
            sheet.addCell(new Label(5, row, item.getMajor()));
            sheet.addCell(new Label(6, row, item.getGrade()));
            sheet.addCell(new Label(7, row, item.getMobile()));
            sheet.addCell(new Label(8, row, item.getEmail()));
            sheet.addCell(new Label(9, row, item.getUsername()));
            sheet.addCell(new Label(10, row, String.valueOf(item.getVoteCount())));
            sheet.addCell(new Label(11, row, DateUtil.format(item.getCreated(), DateUtil.PATTERN_YYYY_MM_DD_HH_MM_SS)));
            sheet.addCell(new Label(12, row, DateUtil.format(item.getUpdated(), DateUtil.PATTERN_YYYY_MM_DD_HH_MM_SS)));
            sheet.addCell(new Label(13, row, competitorStatusLoader.getCodeListMap().get(item.getStatus())));
            sheet.addCell(new Label(14, row, item.getComment()));
            // sheet.addCell(new Label(10, row, item.getPassword()));
        }

        workbook.write();
        workbook.close();
    }
}
